<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="pr-1 m-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-button type="default" @click="handleExport()">
          <Icon icon="ant-design:download-outlined" /> {{ t('导出') }}
        </a-button>
        <a-button type="default" :loading="teacherLoading" @click="syncDingdingTeachers()">
          <Icon icon="ant-design:redo-outlined" /> {{ t('同步钉钉老师信息') }}
        </a-button>
        <a-button type="primary" @click="handleForm({ op: 'add' })" v-auth="'vke:teacherUser:edit'">
          <Icon icon="fluent:add-12-filled" /> {{ t('新增') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ userCode: record.userCode, op: 'edit' })" :title="record.loginCode">
          {{ record.loginCode }}
        </a>
      </template>

      <template #vMajorTitle="{ column, record }">
        <DictLabel
          v-if="record.vteacher"
          :dictType="column.dictType"
          :dictValue="record.vteacher.majorTitle"
        />
      </template>
      <template #vSex="{ column, record }">
        <DictLabel
          v-if="record.vteacher"
          :dictType="column.dictType"
          :dictValue="record.vteacher.sex"
        />
      </template>
      <template #vIsHeadmaster="{ column, record }">
        <DictLabel
          v-if="record.vteacher"
          :dictType="column.dictType"
          :dictValue="record.vteacher.isHeadmaster"
        />
      </template>
      <template #vSubstituteClass="{ column, record }">
        <DictLabel
          v-if="record.vteacher"
          :dictType="column.dictType"
          :dictValue="record.vteacher.substituteClass"
        />
      </template>
      <template #isNail="{ record }">
        {{ record.vteacher.isNail == 2 ? '是' : '否' }}
      </template>
      <template #vSubstituteGrade="{ column, record }">
        <DictLabel
          v-if="record.vteacher"
          :dictType="column.dictType"
          :dictValue="record.vteacher.substituteGrade"
        />
      </template>
      <template #vTeacherType="{ column, record }">
        <DictLabel
          v-if="record.vteacher"
          :dictType="column.dictType"
          :dictValue="record.vteacher.teacherType"
        />
      </template>
      <template #vUserStatus="{ column, record }">
        <DictLabel
          v-if="record.vteacher"
          :dictType="column.dictType"
          :dictValue="record.vteacher.status"
        />
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <FormAuthDataScope @register="registerAuthDataSourceDrawer" @success="handleSuccess" />
    <FormImport @register="registerImportModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsVkeTeacherUserList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, watch, ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { DictLabel } from '/@/components/Dict';

  import { teacherUserDelete, teacherUserListData, teacherUserList } from '/@/api/vke/teacherUser';
  import {
    resetpwd,
    teacherUserDisable,
    teacherUserEnable,
    syncDingdingteacher,
  } from '/@/api/vke/teacherUser';

  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import FormAuthDataScope from './formAuthDataScope.vue';
  import FormImport from './formImport.vue';
  //teacherUser   TeacherUser
  const props = defineProps({
    treeCode: String,
  });
  const param = ref({});
  const { t } = useI18n('vke.teacherUser');
  const { showMessage } = useMessage();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'simple-line-icons:user',
    value: router.currentRoute.value.meta.title || t('学员管理'),
  };
  const teacherLoading = ref(false);
  const ctrlPermi = ref('');
  const postList = ref<Recordable>([]);
  const roleList = ref<Recordable>([]);

  const searchForm: FormProps = {
    baseColProps: { lg: 4, md: 4 },
    labelWidth: 100,
    schemas: [
      {
        label: t('账号'),
        field: 'loginCode',
        component: 'Input',
      },
      {
        label: t('工号'),
        field: 'vteacher.jobNumber',
        component: 'Input',
      },
      {
        label: t('姓名'),
        field: 'refName',
        component: 'Input',
      },
      {
        label: t('性别'),
        field: 'vteacher.sex',
        component: 'Input',
      },
      {
        label: t('是否班主任'),
        field: 'vteacher.isHeadmaster',
        component: 'Select',
        componentProps: {
          dictType: 'sys_yes_no',
        },
      },
      {
        label: t('年级'),
        field: 'vteacher.substituteGrade',
        component: 'Select',
        componentProps: {
          dictType: 'vke_grade',
          allowClear: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('班级'),
        field: 'vteacher.substituteClass',
        component: 'Select',
        componentProps: {
          dictType: 'vke_class',
          allowClear: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('是否绑定钉钉'),
        field: 'vteacher.isNail',
        component: 'Select',
        componentProps: {
          dictType: 'vke_isNail_no',
        },
      },
      // {
      //   label: t('手机'),
      //   field: 'mobile',
      //   component: 'Input',
      // },
      // {
      //   label: t('邮箱'),
      //   field: 'email',
      //   component: 'Input',
      // },
      // {
      //   label: t('电话'),
      //   field: 'phone',
      //   component: 'Input',
      // },
      // {
      //   label: t('岗位'),
      //   field: 'employee.postCode',
      //   component: 'Select',
      //   componentProps: {
      //     options: postList,
      //     allowClear: true,
      //   },
      // },
      // {
      //   label: t('角色'),
      //   field: 'roleCode',
      //   component: 'Select',
      //   componentProps: {
      //     options: roleList,
      //     allowClear: true,
      //   },
      // },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('登录账号'),
      dataIndex: 'loginCode',
      key: 'a.login_code',
      sorter: true,
      width: 100,
      slots: { customRender: 'firstColumn' },
    },
    {
      title: t('工号'),
      dataIndex: 'vteacher.jobNumber',
      key: 'e.job_number',
      sorter: true,
      width: 100,
    },
    {
      title: t('教师姓名'),
      dataIndex: 'refName',
      key: 'a.ref_name',
      sorter: true,
      width: 100,
    },
    // {
    //   title: t('学籍状态'),
    //   dataIndex: 'vstudent.studentStatus',
    //   key: 'e.student_status',
    //   sorter: true,
    //   width: 80,
    //   dictType: 'vke_student_status',
    //   slots: { customRender: 'vStatus' },
    // },
    {
      title: t('性别'),
      dataIndex: 'vteacher.sex',
      key: 'e.sex',
      sorter: true,
      width: 80,
      dictType: 'sys_user_sex',
      slots: { customRender: 'vSex' },
    },
    {
      title: t('出生年月'),
      dataIndex: 'vteacher.dateBirth',
      key: 'e.date_birth',
      sorter: true,
      width: 80,
    },
    {
      title: t('职称'),
      dataIndex: 'vteacher.majorTitle',
      key: 'e.major_title',
      sorter: true,
      width: 80,
      dictType: 'vke_duty',
      slots: { customRender: 'vMajorTitle' },
    },
    {
      title: t('代课科目'),
      dataIndex: 'vteacher.substituteSubjects',
      key: 'e.substitute-subjects',
      sorter: true,
      width: 80,
      // dictType: 'vke_substitute-subjects',
      // slots: { customRender: 'vSubstituteSubjects' },
    },
    {
      title: t('教师类型'),
      dataIndex: 'vteacher.teacherType',
      key: 'e.teacher_type',
      sorter: true,
      width: 80,
      dictType: 'vke_teacher_type',
      slots: { customRender: 'vTeacherType' },
    },
    {
      title: t('班主任'),
      dataIndex: 'vteacher.isHeadmaster',
      key: 'e.is_headmaster',
      sorter: true,
      width: 80,
      dictType: 'sys_yes_no',
      slots: { customRender: 'vIsHeadmaster' },
    },
    {
      title: t('代课年级'),
      dataIndex: 'vteacher.substituteGrade',
      key: 'e.substitute_grade',
      sorter: true,
      width: 80,
      dictType: 'vke_grade',
      slots: { customRender: 'vSubstituteGrade' },
    },
    {
      title: t('代课班级'),
      dataIndex: 'vteacher.substituteClass',
      key: 'e.substitute_class',
      sorter: true,
      width: 80,
      dictType: 'vke_class',
      slots: { customRender: 'vSubstituteClass' },
    },
    {
      title: t('是否绑定钉钉'),
      dataIndex: 'vteacher.isNail',
      key: 'isnail',
      sorter: true,
      width: 80,
      slots: { customRender: 'isNail' },
    },
    {
      title: t('更新时间'),
      dataIndex: 'updateDate',
      key: 'a.update_date',
      sorter: true,
      width: 130,
    },
    // {
    //   title: t('状态'),
    //   dataIndex: 'vteacher.status',
    //   key: 'e.status',
    //   sorter: true,
    //   width: 80,
    //   dictType: 'sys_status',
    //   slots: { customRender: 'vUserStatus' },
    // },
    //  {
    //   title: t('状态'),
    //   dataIndex: 'status',
    //   key: 'a.status',
    //   sorter: true,
    //   width: 80,
    //   dictType: 'sys_status',
    // },
  ];

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑用户'),
        onClick: handleForm.bind(this, { userCode: record.userCode, op: 'edit' }),
        auth: 'vke:teacherUser:edit',
      },
      // {
      //   icon: 'ant-design:stop-outlined',
      //   color: 'error',
      //   title: t('停用用户'),
      //   popConfirm: {
      //     title: t('是否确认停用用户'),
      //     confirm: handleDisable.bind(this, { userCode: record.userCode }),
      //   },
      //   auth: 'vke:studentUser:updateStatus',
      //   ifShow: () => record.status === '0',
      // },
      // {
      //   icon: 'ant-design:check-circle-outlined',
      //   color: 'success',
      //   title: t('启用用户'),
      //   popConfirm: {
      //     title: t('是否确认启用用户'),
      //     confirm: handleEnable.bind(this, { userCode: record.userCode }),
      //   },
      //   auth: 'vke:studentUser:updateStatus',
      //   ifShow: () => record.status === '2',
      // },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除用户'),
        popConfirm: {
          title: t('是否确认删除用户'),
          confirm: handleDelete.bind(this, { userCode: record.userCode }),
        },
        auth: 'vke:teacherUser:edit',
      },
    ],
    dropDownActions: (record: Recordable) => [
      {
        icon: 'ant-design:check-square-outlined',
        label: t('分配角色'),
        onClick: handleForm.bind(this, { userCode: record.userCode, op: 'auth' }),
        auth: 'vke:teacherUser:authRole',
      },
      {
        icon: 'ant-design:check-circle-outlined',
        label: t('数据权限'),
        onClick: handleFormAuthDataScope.bind(this, { userCode: record.userCode, op: 'auth' }),
        auth: 'vke:teacherUser:authDataScope',
      },
      {
        icon: 'ant-design:reload-outlined',
        label: t('重置密码'),
        onClick: handleResetpwd.bind(this, { userCode: record.userCode }),
        auth: 'vke:teacherUser:resetpwd',
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerAuthDataSourceDrawer, { openDrawer: openAuthDataScopeDrawer }] = useDrawer();
  const [registerTable, { reload, getForm }] = useTable({
    api: teacherUserListData,
    beforeFetch: (params) => {
      params.ctrlPermi = ctrlPermi.value;
      params.userType = 'teacher';
      param.value = params;
      return params;
    },
    immediate: false,
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
  });

  onMounted(async () => {
    const res = await teacherUserList();
    postList.value = res.postList?.map((item) => ({
      label: item.postName,
      value: item.postCode,
    }));
    roleList.value = res.roleList?.map((item) => ({
      label: item.roleName,
      value: item.roleCode,
    }));
    ctrlPermi.value = res.ctrlPermi || '2';
    reload();
  });

  watch(
    () => props.treeCode,
    async () => {
      await getForm().setFieldsValue({
        'employee.office.officeCode': props.treeCode,
      });
      reload();
    },
  );

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function syncDingdingTeachers() {
    teacherLoading.value = true;
    let res = await syncDingdingteacher();
    console.log(res);
    if (res) {
      showMessage('后台同步中，时间较长请稍等');
    }
    teacherLoading.value = false;
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    console.log(param.value);
    var _result = [];
    for (var key in param.value) {
      if (key != 'pageSize') {
        _result.push(key + '=' + param.value[key]);
      }
    }
    console.log(_result);
    downloadByUrl({
      url: ctxAdminPath + '/vke/teacherUser/exportData' + '?' + _result.join('&'),
      target: '_self',
    });
  }

  const [registerImportModal, { openModal: importModal }] = useModal();

  function handleImport() {
    importModal(true, {});
  }

  async function handleDisable(record: Recordable) {
    const res = await teacherUserDisable(record);
    showMessage(res.message);
    handleSuccess(record);
  }

  async function handleEnable(record: Recordable) {
    const res = await teacherUserEnable(record);
    showMessage(res.message);
    handleSuccess(record);
  }

  async function handleDelete(record: Recordable) {
    const res = await teacherUserDelete(record);
    showMessage(res.message);
    handleSuccess(record);
  }

  function handleFormAuthDataScope(record: Recordable) {
    openAuthDataScopeDrawer(true, record);
  }

  async function handleResetpwd(record: Recordable) {
    const res = await resetpwd(record);
    showMessage(res.message);
  }

  function handleSuccess(_record: Recordable) {
    reload();
  }
</script>
